package com.mywork.mvpkodeinxml.common

import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import com.uber.autodispose.autoDisposable
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/*防止重复点击
* */
fun View.setThrottlOnClickListener(lifecycleOwner: LifecycleOwner,action: View.OnClickListener) =
    Observable.create(ViewClickOnSubscribe(this))
        .throttleFirst(800, TimeUnit.MILLISECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY))
        .subscribe { view -> action.onClick(view) }

private class ViewClickOnSubscribe(private val view: View) : ObservableOnSubscribe<View> {

    @Throws(Exception::class)
    override fun subscribe(@io.reactivex.annotations.NonNull e: ObservableEmitter<View>) {
        val listener = View.OnClickListener {
            if (!e.isDisposed) {
                e.onNext(view)
            }
        }
        view.setOnClickListener(listener)
    }
}